iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0
Software Development

從零開始的自動化QA學習之路系列 第 8

0x08 Pytest測試框架 教學

  • 分享至 

  • xImage
  •  

About Pytest

pytest 是整合了 setup/teardown, fixture 等等做測試常用的功能的一個測試框架, 本文會將 pytest 作為api test 來使用
奉上官網:
https://docs.pytest.org/en/7.1.x/

前言

下面這篇寫得很詳細, 如果有基礎的大大也滿建議直接跟著做一遍
基於 Pytest 框架的自動化測試開發實踐 (萬字長文入門篇)
https://iter01.com/504335.html

install

$ pip3 install pytest
$ pytest --version
如果有版本跑出來表示安裝成功, 沒有的話可能要debug一下

getting started

$ cat test_first.py //這邊意思是建立一個 test_first.py 的檔案, 用指令偷懶一下xD
內容輸入

def test_first_testcase():
    print("hihihihi")
    assert 1 == 1

$ pytest
$ pytest test_first.py
$ pytest test_first.py::test_first_testcase
以上三個指令都可以執行成功, 預期結果會 1個pass, 但這時候不會看到 hihihihi 的顯示, 因為預設通過就不會顯示print的東西, 錯誤時就會顯示, 所以可以使用他提供的變數
$ pytest test_first.py --capture=no
這樣就把顯示都印出來, 方便debug

pytest 的格式

pytest runtime(就是pytest程式本身), 他會認識 test_abc.py這樣前綴帶test的檔案, 並且function名稱也要前綴test, 所以 def test_first.py 也是為了讓 pytest 能抓得到才這樣取名

使用 Makefile

$ cat Makefile
加入以下內容

run:
    pytest test_first.py::test_first_testcase --capture=no

$ make run
這時候應該會得到相同的實行結果, 但是指令變短了很多, 非常方便推薦使用

fixture

cat test_second.py

import pytest

@pytest.fixture()
def my_data():
    return "dataset"

class MyTest2:
    def test_second_testcase(self, my_data):
        print("data: ", my_data)
        assert my_data == "dataset"

$ pytest test_second.py::MyTest2::test_second_testcase --capture=no
預期結果pass, 並會看到 data: dataset

說明:

  1. 為了使用pytest關鍵字(fixture要用), 所以要import pytest
  2. @pytest.fuxture 這一行下方的function就會被轉成fixture, fixture可以當作參數直接傳到 testcase內.
  3. fixture被視為設定檔, 所以pytest提供了conftest.py的設定檔來存放所有fixture

conftest.py

將上方 fixture 區塊內的程式碼 fixture 部份拆分到設定檔 conftest.py 內
cat conftest.py

import pytest

@pytest.fixture()
def my_data():
    return "dataset"

fixture 進階

剛剛的 fixture 不能傳入參數(因為是資料), 所以這次目標把 fixture做成function
cat test_fourth.py

import pytest

@pytest.fixture()
def get_user_id():
    def fn(user_id):
        return user_id
    return fn

class MyTest4:
    def test_fourth_testcase(self, get_user_id):
        user_id = get_user_id("jackie")
        assert user_id == "jackie"

$ pytest test_fourth.py
預期結果 pass
說明:
傳入參數 get_user_id 就是 這個function的指標(記憶體位置)
所以當我們做 function call 並傳入 "jackie" 的時候, function 才真正執行並return回 "jackie"
自己工作上的程式大量使用這個結構去完成一些測試案例, 不確定是不是 best practice, 但自己覺得滿好用的


上一篇
0x07 Python 語法基礎
下一篇
0x08.5 API 測試
系列文
從零開始的自動化QA學習之路9
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
obarisk
iT邦研究生 2 級 ‧ 2022-09-08 16:20:58

makefile 加個 phony 比較好。

test 應該會用 test 當 phony 吧

yale918 iT邦新手 5 級 ‧ 2022-09-08 22:24:33 檢舉

謝謝大大幫補充, 我有補在0x05 Makefile那邊, 非常感謝^^

我要留言

立即登入留言